<template>
  <div class="ImportXlsx">
    <!-- 导入，下载模板 -->
    <!-- 按钮组件导入、导出、下载模板 -->
    <el-button icon="el-icon-download" type="success" plain @click="exportXlsx" size="mini" :disabled="disabledImport">导出Excel</el-button>
    <!-- :disabled="disabledImport" -->
    <el-button icon="el-icon-upload2" type="success" plain @click="importDialog=true" size="mini">导入Excel</el-button>
    <el-button icon="el-icon-download" type="success" plain @click="downloadTemplate" size="mini">下载模板</el-button>

    <!-- 弹窗 -->
    <el-dialog title="导入" :visible.sync="importDialog" width="780px" :before-close="handleClose">
      <!-- <el-upload
      class="upload-demo"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-change="handleChange"
      :file-list="fileList">
      <el-button size="small" type="primary">选择要导入的文件</el-button>
    </el-upload> -->
      <el-upload class="upload-demo" ref="upload" :headers='{Authorization:$store.state.user.token}' :action='importUrl' :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :on-success="handleSuccess" :on-error="handleError" :auto-upload="false">
        <!-- :on-error='onError' -->
        <!-- :on-change="handleChange" -->
        <!-- <el-dropdown-menu></el-dropdown-menu> -->
        <el-button slot="trigger" size="small" type="primary">选择要导入的文件</el-button>
        <!-- <el-button slot="trigger" size="small" type="primary">{{importUrl}}选择要导入的文件</el-button> -->
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">确认上传</el-button>
        <!-- <div slot="tip" class="el-upload__tip"></div> -->
      </el-upload>
      <!-- <el-progress :percentage="50"></el-progress> -->
    </el-dialog>
  </div>
</template>

<script>
import {
  exportFailData //导出错误表格
} from "@/api/collection/base/flDeviceInfo/index";
export default {
  name: 'ImportXlsx',
  props: [
    'suoS',
    'multipleSelection',
    'importUrl',
    'disabledImport',
    'nbBtnCommon',
  ],
  data () {
    return {
      // 导入窗口开关
      importDialog: false,
      //   // 上传数据
      fileList: [],
      disableExportData: false,
    }
  },
  methods: {
    // 弹窗关闭
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done()
        })
        .catch((_) => { })
    },
    // 上传的方法
    submitUpload () {
      this.$refs.upload.submit()
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },

    handleSuccess (res, file, fileList) {
      this.errRes = res.data
      if (res.flag && res.data) {
        this.$alert(res.message, "导入成功：", {
          dangerouslyUseHTMLString: true,
          // showCancelButton:true,
          cancelButtonText: "确定",
          confirmButtonText: "导出错误信息",
          message: res.message,
          // message:res.message+"<button onclick='this.daochuClick(this.errRes)'>导出错误信息</button>",
          callback: async action => {
            // 刷新页面
            this.$emit('handleSuccessImport', '导入成功')
            console.log(res, 855);
            let key = res.data
            const result = await exportFailData(key)
            console.log(result);
            // let iconv = require('iconv-lite');
            // iconv.skipDecodeWarning = true;//忽略警告
            // let fileName = iconv.decode(result.filename, 'utf-8');
            // let fenge =fileName.split(';')[1]
            // fileName = fenge.split('=')[1]
            // console.log(fileName,'文件名');
            console.log(result, '导出结果');
            let fileName = decodeURI(
              result["filename"].split("=")[1]
            );
            // debugger
            let blob = new Blob([result], { type: "application/vnd.ms-excel;charset=utf-8" });
            var downloadA = document.createElement('a')
            downloadA.download = fileName
            downloadA.style.display = 'none'
            downloadA.href = URL.createObjectURL(blob)
            document.body.appendChild(downloadA)
            downloadA.click()
            URL.revokeObjectURL(downloadA.href)
            document.body.removeChild(downloadA)
            // 提示
            this.$notify({
              title: '导出成功',
              message: fileName,
              type: 'success'
            });
            //   console.log(result);
          }

        });
        // 提醒
        // this.$message({
        //   message:res.message,
        //   type:'success'
        // })
        // this.$emit('handleSuccessImport','导入成功')
      }
      else if (res.flag && !res.data) {
        this.$alert(res.message, "导入成功：", {
          confirmButtonText: "确定",
          callback: action => {
            this.$emit('handleSuccessImport', '导入成功')
          }
        });

      }
      else {
        this.$alert(res.message, "导入失败：", {
          confirmButtonText: "确定",
          callback: action => {
            // this.$message({
            //   type: "warning",
            //   message: res.message
            // });
          }
        });
      }
      // if (res.flag) {
      //   // 提醒
      //   this.$message({
      //     message: res.message,
      //     type: 'success',
      //   })
      //   this.$emit('handleSuccessImport', '导入成功')
      // } else {
      //   this.$alert(res.message, '导入失败：', {
      //     confirmButtonText: '确定',
      //     callback: (action) => {},
      //   })
      // }
      // 清空数组
      this.fileList = []
      // 关闭窗口
      this.importDialog = false
    },
    handleError (res, file, fileList) {
      console.log(res, file, fileList, '失败')
    },

    // 导出方法
    async exportXlsx () {
      console.log('导出Xlsx', this.$parent.exprotXlsx, 777)
      console.log(222)

      try {
        const { exprotXlsx } = this.$parent
        // console.log(exprotXlsx);
        // ----------------获取ids--------------------------------------------------------
        const suoSs = this.suoS
        let multipleSelections = this.multipleSelection
        console.log(multipleSelections, 999)
        let ids = []
        for (let i = 0; i < multipleSelections.length; i++) {
          const element = multipleSelections[i]
          ids.push(element.id)
        }
        console.log(ids, '导出参数')
        console.log(suoSs, ids, '导出参数')
        const length = ids.length
        console.log(length, 77555)

        let res = ''
        let idsq = 'ids'
        console.log()

        if (length) {
          console.log(ids, suoSs, 'ids8')

          res = await exprotXlsx(ids, suoSs)
        } else {
          console.log('ids', 'idsq')
          res = await exprotXlsx('ids', suoSs)
        }

        console.log(res, '导出结果')

        console.log(res, '导出结果')
        let fileName = decodeURI(res['filename'].split('=')[1])
        // let blob = new Blob([res], {type: "application/vnd.ms-excel"});
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8',
        })
        var downloadA = document.createElement('a')
        downloadA.download = fileName
        downloadA.style.display = 'none'
        downloadA.href = URL.createObjectURL(blob)
        document.body.appendChild(downloadA)
        downloadA.click()
        URL.revokeObjectURL(downloadA.href)
        document.body.removeChild(downloadA)
        // 提示
        this.$notify({
          title: '导出成功',
          message: fileName,
          type: 'success',
        })
      } catch (error) {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: '下载失败！',
        })
      }
    },
    // 模板下载
    async downloadTemplate () {
      console.log('模板下载', this.$parent.downloadFile, 6626)
      try {
        const { downloadFile } = this.$parent
        const res = await downloadFile()
        console.log(2222)

        // const res = await this.$parent.downloadFile()
        // let iconv = require('iconv-lite');
        // iconv.skipDecodeWarning = true;//忽略警告
        // let fileName = iconv.decode(res.filename, 'utf-8');
        // let fenge =fileName.split(';')[1]
        // fileName = fenge.split('=')[1]
        console.log(res, '导出结果')
        let fileName = decodeURI(res['filename'].split('=')[1])
        // const blob  = new Blob([res],{type: 'application/vnd.ms-excel;charset=utf-8'})
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        var downloadA = document.createElement('a')
        downloadA.download = fileName
        downloadA.style.display = 'none'
        downloadA.href = URL.createObjectURL(blob)
        document.body.appendChild(downloadA)
        downloadA.click()
        URL.revokeObjectURL(downloadA.href)
        document.body.removeChild(downloadA)
        // 提示
        this.$notify({
          title: '下载模板成功',
          message: fileName,
          type: 'success',
        })
      } catch (error) {
        console.log(error)
        this.$notify.error({
          title: '错误',
          message: '下载失败！',
        })
      }
    },
  },
  created () {
    // this.disabledExport()
  },
  wacth: {
    disabledImport (newValue) {
      this.disabledImport = newValue
    },
  },
  // watch:{
  //   disabledExport(newValue){
  //     this.disabledExport = newValue
  //     this.disabledExport()
  //   }
  // }
}
</script>

<style lang="scss" scoped>
.ImportXlsx {
  display: inline-block;
}
</style>
